import React, { useState, useMemo, useEffect } from "react";
import { Form, Input, Radio } from "antd";
import { ModalComponent } from "@/components/iteration";
import PropTypes from "prop-types";

import rules from "@/config/rules";

/**
 * 添加/修改信息对话框
 *
 * @param {Object} initialValues 初始化数据
 * @param {Function} callback 回调函数
 * @returns {React.Component} Component
 */
const EditorModelComponent = ({ open, initialValues, onCallback, onCancel, ...resProps }) => {
  const [form] = Form.useForm();
  const isEditor = useMemo(() => initialValues && initialValues.dictId, [initialValues]);
  const [confirmLoading, setConfirmLoading] = useState(false);

  useEffect(() => {
    open && form.setFieldsValue(initialValues);
    return () => form.resetFields();
  }, [open, initialValues, form]);

  const onModalOK = () => {
    form.validateFields().then(async (values) => {
      setConfirmLoading(true);
      if (isEditor) {
        values.dictId = initialValues.dictId;
      }
      await onCallback(values).finally(() => setConfirmLoading(false));
      onCancel && onCancel();
    });
  };

  return (
    <ModalComponent
      title={isEditor ? "修改信息" : "添加信息"}
      {...resProps}
      open={open}
      initialValues={{ status: 0 }}
      onOk={onModalOK}
      onCancel={onCancel}
      confirmLoading={confirmLoading}
      destroyOnClose
      forceRender
    >
      <Form
        className="modal-form-card"
        initialValues={{ status: 0 }}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        autoComplete="off"
        form={form}
      >
        <Form.Item name="dictName" label="字典名称" rules={rules.required}>
          <Input placeholder="请输入字典名称" />
        </Form.Item>
        <Form.Item name="dictType" label="字典类型" rules={rules.required}>
          <Input placeholder="请输入字典类型" />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Radio.Group>
            <Radio value={0}>正常</Radio>
            <Radio value={1}>停用</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </ModalComponent>
  );
};
EditorModelComponent.propTypes = {
  open: PropTypes.bool.isRequired,
  initialValues: PropTypes.shape({
    dictId: PropTypes.string || PropTypes.number,
  }),
  onCallback: PropTypes.func.isRequired,
  onCancel: PropTypes.func,
  onClosed: PropTypes.func,
};

export default EditorModelComponent;
